$(document).ready(function() {
    $.getJSON('/backend/get-data?data=product-all-names', function(source) {
        $('input[data-provide="typeahead"]').data('source', source)
    })

    $('#date-submit').click(function(e) {
        var date = $('#date-input').val()
        if(! date)
            return

        var regex = /(\d{4})-(\d{2})-(\d{2})/
        var show_btn = $('#show-form')
        if(regex.test(date)) {
            $('#entry-form .target-date').html(date)
        }

        $.get('/backend/plan/daily', {date: date}, function(html) {
            $('.weekday-plan').remove()
            show_btn.before(html)
        })
    })

    $('#show-form').click(function(e) {
        if(! $('#entry-form .target-date').html())
            return
        $('#entry-form').slideDown()
    })

    $('#add-entry').click(function(e) {
        var date = $('#entry-form .target-date').html()
        var name = $('#input-item-name').val()
        var price = $('#input-price').val()
        var limit = $('#input-limit').val()

        if(! (date && name && price && limit))
            return
        var data = {
            date: date
            , name: name
            , price: price
            , limit: limit
        }
        $.post('/backend/plan/add', data, function(html) {
            $('.weekday-plan').remove()
            $('#show-form').before(html)
            $('#cancel-entry').click()
        })
    })

    $('#cancel-entry').click(function(e) {
        $('#entry-form .control-group input').val('')
        $('#entry-form').slideUp()
    })
})
